import 'package:fluent_ui/fluent_ui.dart';

import '../../api/school_grade_subject_api.dart';
import '../../components/data_table.dart';
import '../../model/school_grade_subject_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';
import '../app/app_school_data.dart';

abstract class SchoolGradeSubjectField {}

///学校年级学科:查询字段
enum SchoolGradeSubjectQueryField implements SchoolGradeSubjectField {
  semester('学年学期'),
  grade('年级'),
  status('状态');

  final String label;

  const SchoolGradeSubjectQueryField(this.label);
}

///学校年级学科:输入字段
enum SchoolGradeSubjectInputField implements SchoolGradeSubjectField {
  semester('学年学期', checked: true),
  grade('年级', checked: true),
  subject('科目', checked: true),
  scoreValue('默认分数'),
  discount('折算比例'),
  remark('备注'),
  status('状态', isAdd: false);

  final String label;
  final bool checked, isAdd;

  const SchoolGradeSubjectInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler<T>(final T? val) {
    if (checked) {
      if (val == null) {
        return '$label不能为空';
      }
      if (val is String) {
        return val.isEmpty ? '$label不能为空' : null;
      }
      if (val is List) {
        return val.isEmpty ? '$label不能为空' : null;
      }
    }
    return null;
  }
}

/// 学校年级学科-视图模型
class SchoolGradeSubjectViewModel extends ChangeNotifier {
  //查询字典
  final _queryFields = <SchoolGradeSubjectQueryField, TextEditingController>{
    for (var field in SchoolGradeSubjectQueryField.values)
      field: TextEditingController(),
  };

  //输入字段
  final _inputFields = <SchoolGradeSubjectInputField, TextEditingController>{
    for (var field in SchoolGradeSubjectInputField.values)
      field: TextEditingController(),
  };

  //获取控制器
  TextEditingController? getController<T extends SchoolGradeSubjectField>(
    final T field,
  ) {
    //查询字段
    if (field is SchoolGradeSubjectQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is SchoolGradeSubjectInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends SchoolGradeSubjectField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends SchoolGradeSubjectField, V>(T field, V val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = '$val';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];
  final _subjectOpts = <ComboBoxItem<String>>[];
  final _schoolSemesterOpts = <String, List<ComboBoxItem<String>>>{};
  final _schoolGradeOpts = <String, List<ComboBoxItem<String>>>{};

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///获取科目选项集合
  List<ComboBoxItem<String>> get subjectOpts => _subjectOpts;

  ///获取学校学年学期选项集合
  List<ComboBoxItem<String>> semestersBySchool(final String schoolId) =>
      _schoolSemesterOpts[schoolId] ?? [];

  ///获取学校年级选项集合
  List<ComboBoxItem<String>> gradesBySchool(final String schoolId) =>
      _schoolGradeOpts[schoolId] ?? [];

  ///获取学年学期标题
  String getSemesterTitle(final String schoolId, semesterId) => appSchoolData
      .getSemesterLabel(schoolId: schoolId, semesterId: semesterId);

  ///获取学校年级
  String getGradeTitle(final String schoolId, final int? gradeVal) =>
      appSchoolData.getGradeLabel(schoolId: schoolId, gradeVal: gradeVal);

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then(
        (opts) {
          if (opts.isNotEmpty) {
            _statusOpts.addAll(opts);
          }
        },
      );
      futures.add(future);
    }
    //科目
    if (_subjectOpts.isEmpty) {
      final future = appDictData.buildOpts('subject').then(
        (opts) {
          if (opts.isNotEmpty) {
            _subjectOpts.addAll(opts);
          }
        },
      );
      futures.add(future);
    }
  }

  ///加载学校学年学期
  void _loadSemesters(String schoolId, List<Future<dynamic>> futures) {
    //检查学校ID
    if (schoolId.isEmpty) {
      return;
    }
    //加载数据
    final future = appSchoolData
        .buildSemesterOpts(schoolId)
        .then((opts) => _schoolSemesterOpts[schoolId] = opts);
    futures.add(future);
  }

  ///加载学校年级
  void _loadGrades(String schoolId, List<Future<dynamic>> futures) {
    if (schoolId.isEmpty) {
      return;
    }
    //加载数据
    final future = appSchoolData
        .buildGradeOpts(schoolId)
        .then((opts) => _schoolGradeOpts[schoolId] = opts);
    futures.add(future);
  }

  ///加载初始化
  void loadInit(final String schoolId, {VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //加载学校学年学期
    _loadSemesters(schoolId, futures);
    //加载学校年级
    _loadGrades(schoolId, futures);
    //请求同步
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      //通知处理
      notifyListeners();
    }
    //后续处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  ///清空查询字段
  void cleanQueryFields() {
    for (var ctl in _queryFields.values) {
      ctl.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var ctl in _inputFields.values) {
      ctl.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SchoolGradeSubjectItemRes>();

  ///分页查询
  void query(final String schoolId) async {
    try {
      loading.showLoading();
      //查询条件
      final grade = getFieldValue(SchoolGradeSubjectQueryField.grade);
      final status = getFieldValue(SchoolGradeSubjectQueryField.status);
      final req = SchoolGradeSubjectQueryReq(
        schoolId: schoolId,
        semesterId: getFieldValue(SchoolGradeSubjectQueryField.semester) ?? '',
        gradeVal: int.tryParse(grade ?? '') ?? 0,
        status: int.tryParse(status ?? '') ?? -1,
        index: queryModel.current,
        size: queryModel.size,
      );
      //查询数据
      final res = await schoolGradeSubjectApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('schoolGradeSubjectApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await schoolGradeSubjectApi.info(id);
      if (res.isSuccessed) {
        //学年学期
        setFieldValue(SchoolGradeSubjectInputField.semester, res.semesterId);
        //年级
        setFieldValue(SchoolGradeSubjectInputField.grade, res.gradeVal);
        //科目
        setFieldValue(SchoolGradeSubjectInputField.subject, res.subjectVal);
        //默认分数
        setFieldValue(SchoolGradeSubjectInputField.scoreValue, res.scoreValue);
        //折算比例
        setFieldValue(SchoolGradeSubjectInputField.discount, res.discount);
        //备注
        setFieldValue(SchoolGradeSubjectInputField.remark, res.remark);
        //状态
        setFieldValue(SchoolGradeSubjectInputField.status, res.status);
        //触发通知
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  BaseSchoolGradeSubjectSaveReq _buildSaveReq() {
    //学年学期
    final semester = getFieldValue(SchoolGradeSubjectInputField.semester);
    //年级
    final grade = getFieldValue(SchoolGradeSubjectInputField.grade);
    //科目
    final subject = getFieldValue(SchoolGradeSubjectInputField.subject);
    //默认分数
    final scoreValue = getFieldValue(SchoolGradeSubjectInputField.scoreValue);
    //折算比例
    final discount = getFieldValue(SchoolGradeSubjectInputField.discount);
    //备注
    return BaseSchoolGradeSubjectSaveReq(
      semesterId: semester ?? '',
      gradeVal: int.tryParse(grade ?? '') ?? 0,
      subjectVal: int.tryParse(subject ?? '') ?? 0,
      scoreValue: int.tryParse(scoreValue ?? '') ?? 100,
      discount: double.tryParse(discount ?? '') ?? 1.0,
      remark: getFieldValue(SchoolGradeSubjectInputField.remark) ?? '',
    );
  }

  ///新增处理
  void onAddHandler(final String schoolId, final VoidCallback handler) async {
    try {
      loading.showLoading();
      final baseReq = _buildSaveReq();
      final req = SchoolGradeSubjectAddReq(
        schoolId: schoolId,
        base: baseReq,
      );
      //新增处理
      final res = await schoolGradeSubjectApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      final baseReq = _buildSaveReq();
      //状态
      final status = getFieldValue(SchoolGradeSubjectInputField.status);
      final req = SchoolGradeSubjectModifyReq(
        id: id,
        status: int.tryParse(status ?? '') ?? 1,
        base: baseReq,
      );
      //修改处理
      final res = await schoolGradeSubjectApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除数据
  void onDeleteHandler({required final String schoolId, id}) async {
    try {
      loading.showLoading();
      //删除处理
      final res = await schoolGradeSubjectApi.delete(id);
      if (res.isSuccessed) {
        query(schoolId);
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
